package com.laoyao.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

import com.laoyao.beans.JsCode;

public class HttpUtil {
	
	
	public static String sendGet(String url){
		String result = "";
		HttpURLConnection conn=null;
		BufferedReader bfr =null;
		URL urler=null;
		try {
			 urler = new URL(url);
			 conn = (HttpURLConnection) urler.openConnection();
			//链接
			conn.connect();
			//各种转，转成BufferedReader

			 bfr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while((line=bfr.readLine())!=null){
				result+=line;
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			conn.disconnect();
			
				try {
					if(bfr!=null)
					bfr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
		
		return result;
	}
	/**
	 * @param appid 小程序的appid
	 * @param secret 小程序的secret
	 * @param code 小程序wx.login()获取到的code用来获取openid、session_key
	 * 
	 */
	
	public static JsCode getJsCode(String appid,String secret,String code){
		JsCode jscode = new JsCode();
		String url = "https://api.weixin.qq.com/sns/jscode2session?"
				   + "appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		//替换参数中的字段
		url=url.replace("APPID", appid);
		url=url.replace("SECRET",secret);
		url=url.replace("JSCODE", code);
		//sendGet 是想微信api发送请求获取openid和session_key
		System.out.println(url);
		String str = sendGet(url);
		JSONObject json =  JSONObject.fromObject(str);
		System.out.println(str);
		//如果请求错误，返回空
		if(json.get("errcode")!=null)
			return null;
		jscode.setOpenid(json.getString("openid"));
		jscode.setSession_key(json.getString("session_key"));	
		return jscode;
	}
	
	

}
